var express = require('express');
var router = express.Router();
var xss = require('xss');
var validate = require('../common/validate.js');
var mongoose = require('mongoose');
var crypto = require('crypto');
var permission = require('../common/permission.js');
var soap = require('soap');
var homeworkSchema = require('../models/homeworkschema.model.js')

router.get('/login', permission.checkNotLogin, login_page);
router.post('/login', login);
router.get('/reg', permission.checkLogin, permission.isLowPosition, register);
router.post('/reg', regist);
router.get('/logout', logout);
router.get('/schk', selfcheck);
router.post('/schk', selfcheck2);
router.get('/detail', ajaxdetail);
router.post('/changeInfo', changeInfo);
router.get('/depMember', ajaxDep);
router.get('/findUser', findUser);
router.get('/chpsw', permission.checkLogin, chpsw);    //修改密码
router.post('/chpsw', chpswPost);    //修改密码

function chpswPost(req, res, next) {
    if (!req.session.user) {
        return res.send('同学别闹!');
    }
    var oldpsw = xss(req.body.oldpsw),
        newpsw = xss(req.body.newpsw),
        repeatpsw = xss(req.body.repeatpsw);
    
    if (newpsw !== repeatpsw) {
        return res.send('<script>alert("两次输入密码不相同");location.href="/user/chpsw";</script>');
    }
    var User = mongoose.model('User');

    User.findById(req.session.user['_id'], function(err, result) {
        if (err) throw err;
        //将输入的旧密码与数据库里的比较
        var md5 = crypto.createHash('md5');
        md5.update(oldpsw);
        oldpsw = md5.digest('hex');

        
        if (oldpsw !== result.password) {
            console.log('数据库密码:'+result.password);
            console.log('输入密码:'+oldpsw);
            return res.send('<script>alert("原密码输入有误!");location.href="/user/chpsw";</script>');
        }

        var md5 = crypto.createHash('md5');
        md5.update(newpsw);
        newpsw = md5.digest('hex');

        User.update({_id: req.session.user['_id']}, {$set: {password: newpsw}}, function(err, result) {
            if (err) throw err;
            console.log(result + '修改密码成功!');
            return res.send('<script>alert("修改密码成功!");location.href="/";</script>')
        })
        
    })
    
}

function chpsw(req, res, next) {
    res.render('user/chpsw', {
        title: '修改密码',
        user: req.session.user
    });
}

function findUser(req, res){
    var User = mongoose.model('User');
    var username = xss(req.query.username);
    console.log('query='+username);
    var reg = new RegExp(username);
    console.log(reg);
    User.find({username: reg}, function(err, results){
        if(err) throw err;
        return res.json(results);
    })
}
function  ajaxDep(req, res, next){
    var User = mongoose.model('User');
    if(req.query.position == 6){
        User.find({department: req.query.department, position: req.query.position}, function(err, results){
            res.json(results);
        })
    }
    else{
        User.find({department: req.query.department, position: {"$lte":5}}, function(err, results){
            res.json(results);
        })
    }
}

function changeInfo(req, res){
    //验证两次输入密码是否相同
    if(xss(req.body.password) != xss(req.body.confirm)){
        return res.send('<script>alert("两次密码输入不一致!");location.href="../admin"</script>')
    } else {
        var newmsg;
        //判断是否修改了密码
        if(req.body.password){
            newmsg = {
                password: crypto.createHash('md5').update(req.body.password).digest('hex'),
                mobile: req.body.mobile,
                roomnumber: req.body.roomnumber,
                mail: req.body.mail,
                dep: req.body.dep,
                birthday: req.body.birthday,
                avatar: req.body.avatar
            };
        } else {
            newmsg = {
                mobile: req.body.mobile,
                roomnumber: req.body.roomnumber,
                mail: req.body.mail,
                dep: req.body.dep,
                birthday: req.body.birthday,
                avatar: req.body.avatar
            };
        }
        var User = mongoose.model('User');
        var userid = req.session.user.userid;
        User.findOne({userid: userid}, function(err, result){
            if(err) throw err;
            if(result){
                User.update({userid: userid}, newmsg, function(err) {
                    if(err) throw err;
                    if(req.body.password){
                        req.session.user = null;//清除登录状态
                        return res.send('<script>alert("修改成功,请重新登录!");location.href="/user/login"</script>')
                    } else{
                        User.findOne({userid: userid}, function(err, result2){
                            if(err) throw err;
                            req.session.user = result2;  //写入session
                        });
                        return res.send('<script>alert("修改成功!");location.href="../admin"</script>')
                    }
                })
            }
        })
    }
}

function ajaxdetail(req, res){
    var userinfo = req.session.user;
    var User = mongoose.model('User');
    User.findOne({userid:userinfo.userid}, function(err, result){
        if (err) console.log(err);
        //console.log(result);
        if(result){
            return res.json(result);
        } else {
            return res.json({exist: 0});
        }
    });
}

function logout(req, res, next) {
    req.session.user = null;
    res.redirect('back');
}

function login_page(req, res, next) {
    res.render('user/login', {
        title: '系统登录'
    });
}

function login(req, res, next) {
    var userid = req.body.userid;
    var password = req.body.password;

    //检查是否存在该用户
    checkUser(userid, password, req, function(obj) {
        res.send(JSON.stringify(obj));
    });

}

function checkUser(userid, password, req, callback) {
    var psw = crypto.createHash('md5').update(password).digest('hex');
    console.log(psw);

    var obj = {
        status: 400,
        msg: '登录成功'
    }

    var User = mongoose.model('User');
    User.findOne({userid: userid, password: psw}, function(err, result) {
        if (err) throw err;

        if (!result) {
            obj.msg = '用户名或密码错误';
        } else {
            console.log(result);
            req.session.user = result;  //写入session
            obj.status = 200;
        }

        callback(obj);
    });
}

//返回录入页面
function register(req, res, next) {
    res.render('user/register', {
        title: '员工信息录入',
        user: req.session.user
    });
}

//员工自主申请
function selfcheck(req, res) {
  res.render('user/selfcheck', {
    title: '员工自主验证',
    user: req.session.user
  })
}

//员工输入netid录入信息到数据库
function selfcheck2(req, res, next) {
  var data = {
    netid: req.body.netid
  };
  if(validate.emptystring(data.netid) || validate.normalstring(data.netid)){
    var User = mongoose.model('User');

    getSiminfo(data.netid, function(msg) {
        if(msg == null){ return res.send('<script>alert("netid不存在!")</script>') }

        //查看主管是否已录入该信息,录入则更新其他数据并设置验证状态为true
        User.find({userno: msg.userno}, function(err, results){
            if(err) throw err;

            if(results.length){
                // console.log(msg);
                if(results[0].validated){
                    return res.send('<script>alert("已经验证过啦~");location.href="schk"</script>');
                }
                var gender;
                if(msg.gender == "女") gender = 1;
                else {gender = 0;}
                //md5加密存入数据库
                var pwd = crypto.createHash('md5').update(msg.userid).digest('hex');
                var newmsg = {
                    userid: msg.userid,
                    username: msg.username,
                    password: pwd,
                    classid: msg.classid,
                    mobile: msg.mobile,
                    mail: msg.email,
                    roomnumber: msg.roomnumber,
                    birthday: msg.birthday,
                    gender: gender,
                    validated: true,
                    dep: msg.dep
                };

                var Homework = mongoose.model('Homework');
                var newStaffModel = {};
                newStaffModel[msg.userid] = homeworkSchema;
                Homework.schema.add(newStaffModel);


                User.update({userno: msg.userno},newmsg,function(err){
                    if(err) throw err;
                    return res.send('<script>alert("验证成功!初始密码为您的netid,快登录试试看吧~");location.href="login"</script>');
                });
            } else{
                console.log('results长度为'+results.length);
                return res.send('<script>alert("你的主管还没录入你的信息哦~")</script>');
            }
        })
    });


  } else {
    res.send('<script>alert("您的输入中包含非法字符！");location.href = "schk"</script>');
  }
}

//传入netid,获取其他信息并传入回调
function getSiminfo(netid, callback) {
    var url = 'http://202.117.1.241/axis2/services/UserInfo?wsdl';
    netid = xss(netid);
    var args = {auth: 'diff',uid: netid};
    soap.createClient(url, function(err, client) {
        client.getInfoById(args, function(err, result) {
            if(err) throw err;
            console.log(result);
            if(result == null){ return callback(null); }
            callback(result.return);
        });
    });
}

//录入信息到数据库
function regist(req, res, next) {

    if (!req.session.user) {
        return res.send('同学别闹!');
    }

    // console.log(req.body.position);
    //获取到表单数据：
    var data = {
        userno: req.body.userno,
        department: req.body.department,
        position: req.body.position,
        note: req.body.note
    };

    var obj = validateMsg(data);

    if (obj.status == 200) {
        var User = mongoose.model('User');
        //检查学号是否存在
        User.find({userno: data.userno}, function(err, results) {
            if (err) throw err;
            console.log(results);
            if (results.length) {
                console.log(results);
                return res.send('<script>alert("用户已存在！")</script>');
            } else {
                ////密码md5后进行保存
                //var datenow = Date.now();
                //var md5 = crypto.createHash('md5');
                //md5.update(datenow);
                //data.password = md5.digest('hex');
                if(!req.session.user) {
                    return res.send('<script>alert("hhh");</script>');
                }

                var user = new User({
                    userno: xss(data.userno),
                    //password: data.password,
                    department: parseInt(data.department),
                    position: parseInt(data.position),
                    note: xss(data.note),
                    avatar: parseInt(Math.random()*12+1)
                });

                user.save(function(err, results) {
                    if (err) throw err;
                    console.log(results);
                });


                return res.send('<script>alert("录入成功！");location.href="reg"</script>');
                //return res.redirect('/user/reg');
            }
        });


    } else {
        console.log(obj.msg);
        return res.send('<script>alert("录入失败！");location.href="reg"</script>');
        //return res.redirect('/user/reg');
    }


}

function validateMsg(data) {
    var obj = {
        status: 400,
        msg: '发送成功，我们会尽快回复您的...'
    }
    if (validate.emptystring(data.userno) || validate.emptystring(data.department) || validate.emptystring(data.position)) {
        obj.msg = '输入为空！';
        return obj;
    }
    if (data.userno.length > 20 || data.department.length > 20 || data.note.length > 200) {
        obj.msg = '字数超限！';
        return obj;
    }
    if (!validate.normalstring(data.userno) || !validate.normalstring(data.department)) {
        obj.msg = '输入中包含非法字符！';
        return obj;
    }

    obj.status = 200;

    return obj;
}


module.exports = router;
